import 'package:awak/common/models/content.dart';
import 'package:awak/common/models/user.dart';
import 'package:awak/common/repository/content_repository.dart';
import 'package:awak/common/repository/favorite_repository.dart';
import 'package:awak/common/routers/router_names.dart';
import 'package:awak/common/utils/util_text.dart';
import 'package:awak/common/values/images.dart';
import 'package:awak/common/values/svg.dart';
import 'package:awak/page/community/content_data_holder.dart';
import 'package:awak/page/profile/user_data_holder.dart';
import 'package:awak/common/utils/util_toast.dart';
import 'package:awak/bloc/auth/auth_bloc.dart';
import 'package:awak/bloc/auth/auth_event.dart';
import 'package:awak/bloc/auth/auth_state.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:beamer/beamer.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class OtherProfilePage extends StatefulWidget {
  const OtherProfilePage({super.key});

  @override
  State<OtherProfilePage> createState() => _OtherProfilePageState();
}

class _OtherProfilePageState extends State<OtherProfilePage> {
  final ContentRepository _contentRepository = ContentRepository();
  final FavoriteRepository _favoriteRepository = FavoriteRepository();

  User? _targetUser;
  List<Content> _userContents = [];
  List<Content> _userFavorites = [];
  bool _isLoading = true;
  int _selectedTabIndex = 0; // 0 = Issue, 1 = Collect
  int _friendsCount = 0;

  @override
  void initState() {
    super.initState();
    _loadUserData();
  }

  Future<void> _loadUserData() async {
    try {
      // 从UserDataHolder获取目标用户
      final user = UserDataHolder.getCurrentUser();
      if (user == null) {
        // 如果没有用户数据，返回上一页
        Beamer.of(context).beamBack();
        return;
      }

      setState(() {
        _targetUser = user;
      });

      // 加载用户发布的内容
      final userContents = await _contentRepository.getContentsByUserId(user.id!);

      // 加载用户收藏的内容
      final favoriteContents = await _favoriteRepository.getFavoriteContentsByUserId(user.id!);

      // 加载好友数量
      final friendsCount = await context.read<AwakBloc>().friendshipRepository.getFriendsCount(user.id!);

      if (!mounted) return;

      setState(() {
        _userContents = userContents;
        _userFavorites = favoriteContents;
        _friendsCount = friendsCount;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_targetUser == null) {
      return Scaffold(
        body: Center(child: CircularProgressIndicator()),
      );
    }

    return Scaffold(
      backgroundColor: Color(0xFFFFE0F4),
      body: SafeArea(
        child: Column(
          children: [
            // 顶部导航栏
            _buildAppBar(),
            SizedBox(height: 20.h),
            // 用户信息卡片
            _buildUserInfoCard(),
            SizedBox(height: 20.h),
            // 切换按钮
            _buildTabButtons(),
            SizedBox(height: 20.h),
            // 内容列表
            Expanded(
              child: _buildContentList(),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildAppBar() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 10.h),
      child: Row(
        children: [
          GestureDetector(
            onTap: () => Beamer.of(context).beamBack(),
            child: Icon(
              AwakSvg.back,
              size: 24.w,
              color: Colors.black,
            ),
          ),
          Expanded(
            child: Text(
              "${_targetUser?.nickname ?? _targetUser?.username ?? 'User'}'S HOMEPAGE",
              textAlign: TextAlign.center,
              style: AwakText.titleStyle.copyWith(
                fontWeight: FontWeight.bold,
                color: Colors.black,
              ),
            ),
          ),
          SizedBox(width: 24.w),
        ],
      ),
    );
  }

  Widget _buildUserInfoCard() {
    final avatar = _targetUser?.avatar ?? AwakImages.avatar;
    final nickname = _targetUser?.nickname ?? _targetUser?.username ?? 'Unknown User';

    return Container(
      margin: EdgeInsets.symmetric(horizontal: 20.w),
      padding: EdgeInsets.all(20.w),
      decoration: BoxDecoration(
        color: Colors.transparent,
        image: DecorationImage(
          image: AssetImage(AwakImages.otherProfileBg),
          fit: BoxFit.fill,
        ),
      ),
      child: Column(
        children: [
          // 用户头像
          Container(
            width: 80.w,
            height: 80.h,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              border: Border.all(color: Colors.black, width: 3.w),
              image: DecorationImage(
                image: AssetImage(avatar),
                fit: BoxFit.cover,
              ),
            ),
          ),
          SizedBox(height: 15.h),
          // 用户名和按钮行
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              // 聊天按钮
              GestureDetector(
                onTap: () {
                  if (_targetUser != null) {
                    Beamer.of(context).beamToNamed(RouterNames.chatProfile, data: _targetUser);
                  }
                },
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
                  decoration: BoxDecoration(
                    color: Colors.black,
                    borderRadius: BorderRadius.circular(15.r),
                  ),
                  child: Icon(
                    AwakSvg.chat,
                    color: Colors.white,
                    size: 16.w,
                  ),
                ),
              ),
              SizedBox(width: 15.w),
              // 用户名
              Text(
                nickname,
                style: AwakText.body16Style.copyWith(
                  fontWeight: FontWeight.bold,
                  color: Colors.black,
                ),
              ),
              SizedBox(width: 15.w),
              // 关注按钮
              BlocListener<AwakBloc, AwakState>(
                listener: (context, state) {
                  if (state is FriendAdded) {
                    AwakToast.showCustomToast(context, state.message);
                    // 重新加载用户数据以更新好友数量
                    _loadUserData();
                  } else if (state is FriendshipFailure) {
                    AwakToast.showCustomToast(context, state.message);
                  }
                },
                child: GestureDetector(
                  onTap: () {
                    final currentUser = context.read<AwakBloc>().userRepository.currentUser;
                    if (currentUser != null && _targetUser != null) {
                      context.read<AwakBloc>().add(
                        AddFriendEvent(currentUser.id!, _targetUser!.id!)
                      );
                    }
                  },
                  child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
                    decoration: BoxDecoration(
                      color: Colors.black,
                      borderRadius: BorderRadius.circular(15.r),
                    ),
                    child: Icon(
                      AwakSvg.follow,
                      color: Colors.white,
                      size: 16.w,
                    ),
                  ),
                ),
              ),
            ],
          ),
          SizedBox(height: 15.h),
          // 统计信息
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              _buildStatCard('${_userContents.length}', 'Issue'),
              _buildStatCard('$_friendsCount', 'Friends'),
              _buildStatCard('${_userFavorites.length}', 'Collect'),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildStatCard(String count, String label) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.r),
        border: Border.all(color: Colors.black, width: 2.w),
      ),
      child: Text(
        '$count/$label',
        style: AwakText.body14Style.copyWith(
          fontWeight: FontWeight.w600,
          color: Colors.black,
        ),
      ),
    );
  }

  Widget _buildTabButtons() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      child: 
    Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        _buildTabButton('Issue', 0),
        SizedBox(width: 20.w),
        _buildTabButton('Collect', 1),
      ],
    ),
    );
  }

  Widget _buildTabButton(String title, int index) {
    final isSelected = _selectedTabIndex == index;
    Color selectedColor;

    // 根据按钮类型设置选中时的颜色
    if (index == 0) { // Issue按钮
      selectedColor = Color(0xFFFFF45C); // 黄色
    } else { // Collect按钮
      selectedColor = Color(0xFFFFF45C); // 绿色
    }

    return GestureDetector(
      onTap: () {
        setState(() {
          _selectedTabIndex = index;
        });
      },
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 14.w, vertical: 10.h),
        decoration: BoxDecoration(
          color: isSelected ? selectedColor : Colors.white,
          borderRadius: BorderRadius.circular(12.r),
          border: Border.all(color: Colors.black, width: 2.w),
        ),
        child: Text(
          title,
          style: AwakText.body16Style.copyWith(
            fontWeight: FontWeight.bold,
            color: Colors.black,
          ),
        ),
      ),
    );
  }

  Widget _buildContentList() {
    if (_isLoading) {
      return Center(child: CircularProgressIndicator());
    }

    final contents = _selectedTabIndex == 0 ? _userContents : _userFavorites;

    if (contents.isEmpty) {
      return Center(
        child: Text(
          _selectedTabIndex == 0 ? 'No posts yet' : 'No collections yet',
          style: AwakText.body16Style.copyWith(
            color: Colors.black.withValues(alpha: 0.6),
          ),
        ),
      );
    }

    return ListView.builder(
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      itemCount: contents.length,
      itemBuilder: (context, index) {
        return _buildContentCard(contents[index]);
      },
    );
  }

  Widget _buildContentCard(Content content) {
    return GestureDetector(
      onTap: () {
        ContentDataHolder.setCurrentContent(content);
        Beamer.of(context).beamToNamed(RouterNames.detailContent);
      },
      child: Container(
        margin: EdgeInsets.only(bottom: 16.h),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 用户信息行
            Row(
              children: [
                Container(
                  width: 40.w,
                  height: 40.h,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    border: Border.all(color: Colors.black, width: 2.w),
                    image: DecorationImage(
                      image: AssetImage(_targetUser?.avatar ?? AwakImages.avatar),
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
                SizedBox(width: 12.w),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        _targetUser?.nickname ?? _targetUser?.username ?? 'Unknown User',
                        style: AwakText.body16Style.copyWith(
                          color: Colors.black,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                      Text(
                        _targetUser?.signature ?? 'No signature',
                        style: AwakText.body14Style.copyWith(
                          color: Colors.black.withValues(alpha: 0.6),
                          fontSize: 12.sp,
                        ),
                      ),
                    ],
                  ),
                ),
                // 标签
                Container(
                  padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(100.r),
                    border: Border.all(color: Colors.black, width: 1.w),
                  ),
                  child: Row(
                    children: [
                      Icon(AwakSvg.report, size: 14.sp),
                      SizedBox(width: 4.w),
                      Text(
                        'Issue',
                        style: AwakText.body14Style.copyWith(
                          color: Colors.black,
                          fontWeight: FontWeight.w500,
                          fontSize: 12.sp,
                        ),
                      ),
                    ],
                  )
                ),
              ],
            ),
            SizedBox(height: 12.h),
            // 内容图片
            Container(
              width: double.infinity,
              height: 223.h,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(12.r),
                image: DecorationImage(
                  image: AssetImage(content.picture),
                  fit: BoxFit.cover,
                ),
              ),
            ),
            SizedBox(height: 12.h),
            // 内容描述
            Text(
              content.description,
              style: AwakText.body16Style.copyWith(
                color: Colors.black,
                fontWeight: FontWeight.w500,
                height: 1.4,
              ),
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
            ),
            SizedBox(height: 20.h),
          ],
        ),
      ),
    );
  }
}